package com.fjp.heartguard.ui.question

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.os.Bundle
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.fjp.heartguard.R
import com.fjp.heartguard.app.Constants
import com.fjp.heartguard.app.base.BaseActivity
import com.fjp.heartguard.app.data.bean.GroupQuestionType
import com.fjp.heartguard.app.data.bean.OlderInfoQuestion
import com.fjp.heartguard.app.data.bean.Questionnaire
import com.fjp.heartguard.app.data.bean.Questions
import com.fjp.heartguard.app.data.bean.Select
import com.fjp.heartguard.app.eventViewModel
import com.fjp.heartguard.app.ext.showToast
import com.fjp.heartguard.app.util.CacheUtil
import com.fjp.heartguard.app.util.DateTimeUtil
import com.fjp.heartguard.databinding.ActivityQuestionSupplementaryInfoBinding
import com.fjp.heartguard.ui.autograph.AutographActivity
import com.fjp.heartguard.ui.report.ReportDetailActivity
import com.fjp.heartguard.viewmodel.QuestionSupplementaryInfoViewModel
import com.github.gzuliyujiang.wheelpicker.DatePicker
import com.github.gzuliyujiang.wheelpicker.annotation.DateMode
import com.github.gzuliyujiang.wheelpicker.contract.OnDatePickedListener
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.github.gzuliyujiang.wheelpicker.impl.UnitDateFormatter
import com.lxj.xpopup.XPopup
import com.zlw.main.recorderlib.RecordManager
import com.zlw.main.recorderlib.recorder.RecordHelper.RecordState
import com.zlw.main.recorderlib.recorder.listener.RecordResultListener
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.network.NetworkUtil
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.time.LocalDate
import java.time.Period
import java.time.temporal.ChronoUnit
import kotlin.math.abs

/**
 * 问卷调查最后的额外信息页面
 */
class QuestionSupplementaryInfoActivity : BaseActivity<QuestionSupplementaryInfoViewModel, ActivityQuestionSupplementaryInfoBinding>(), OnDatePickedListener {
    lateinit var resultLauncher: ActivityResultLauncher<Intent>
    var recordFile: File? = null
    val recordManager = RecordManager.getInstance().setRecordResultListener(object : RecordResultListener {


        override fun onResult(result: File?) {
            recordFile = result
            if (result != null) {
                if (NetworkUtil.isNetworkAvailable(this@QuestionSupplementaryInfoActivity)) {
                    val reqFile = RequestBody.create(MediaType.parse("audio"), result)
                    val body = MultipartBody.Part.createFormData("file", result.name, reqFile)
                    mViewModel.updateRecord(body)
                } else {
                    QuestionActivity.olderInfo.audio_file = result.path
                    commit()
                }

            }

        }
    })

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewModel = mViewModel
        mDatabind.click = ClickProxy()
        mViewModel.title.set("老年人健康追踪评估问卷")
        val currentDate = LocalDate.now()
        mViewModel.date.set("${currentDate.year}-${String.format("%02d", currentDate.monthValue)}-${String.format("%02d", currentDate.dayOfMonth)}")
        resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == RESULT_OK && it.data != null) {
                val path = it.data!!.getStringExtra(Constants.INTENT_SINGLE_PATH)
                val file = File(path)

                if (file.exists()) {
                    val originSignatureBitmap = BitmapFactory.decodeFile(path)
                    val martrix = Matrix()
                    martrix.postRotate(-90f)
                    val showSignatureBitmap = Bitmap.createBitmap(originSignatureBitmap, 0, 0, originSignatureBitmap.width, originSignatureBitmap.height, martrix, true)
                    mDatabind.singlenatureIv.setImageBitmap(showSignatureBitmap)
                }
            }
        }
    }

    private fun showReUploadRecordPop() {
        XPopup.Builder(this).asConfirm("录音上传失败", "是否重新上传", "取消", "上传", {
            val reqFile = RequestBody.create(MediaType.parse("audio"), recordFile)
            val body = MultipartBody.Part.createFormData("file", recordFile!!.name, reqFile)
            mViewModel.updateRecord(body)
        }, {

        }, false).show()
    }

    override fun createObserver() {
        super.createObserver()

        mViewModel.commitLiveData.observe(this) {
            parseState(it, {
                showToast("保存成功")
                eventViewModel.saveQuestionSuccess.postValue(true)
                finish()
                val intent = Intent(this@QuestionSupplementaryInfoActivity, ReportDetailActivity::class.java)
                intent.putExtra(Constants.Intent_OLDER_ID, it.older_id)
                intent.putExtra(Constants.INTENT_REPORT_ID, it.id)
                startActivity(intent)
            }, {
                it.printStackTrace()
                showToast("保存失败")
            }, {
                dismissLoading()
            })
        }
        mViewModel.recordUpdateSuccess.observe(this) {
            commit()
        }
        mViewModel.recordUpdateFailed.observe(this) {
            showReUploadRecordPop()
        }

    }

    inner class ClickProxy {
        fun clickAutograph() {
            resultLauncher.launch(Intent(this@QuestionSupplementaryInfoActivity, AutographActivity::class.java))
        }

        fun clickDate() {
            showDateDialog()
        }

        fun clickCommit() {
            if (QuestionActivity.olderInfo.signature.isEmpty()) {
                showToast("请签名")
                return
            }
            getCommitData()
            if (RecordManager.getInstance().state == RecordState.RECORDING) {
                RecordManager.getInstance().stop()
            } else {
                commit()
            }
        }

    }

    fun commit() {
        QuestionActivity.olderInfo.assess_time = mViewModel.date.get()!!
        QuestionActivity.olderInfo.supplement = mViewModel.supplementaryInfo.get()!!
        if (NetworkUtil.isNetworkAvailable(this)) {
            mViewModel.saveQuestionnaireInfo()
        } else {
            QuestionActivity.olderInfo.created_at = DateTimeUtil.formatDate(System.currentTimeMillis(), DateTimeUtil.DATE_PATTERN_SS)
            val date = QuestionActivity.olderInfo.birthday.split("-")
            if (date.size == 3) {
                val year = date[0].toIntOrNull()
                val month = date[1].toIntOrNull()
                val day = date[2].toIntOrNull()
                if (year != null && month != null && day != null) {
                    val startDate = LocalDate.of(year, month, day)
                    val endDate = LocalDate.now()

                    // 计算两个日期之间的差值
                    val period = Period.between(startDate, endDate)
                    QuestionActivity.olderInfo.age = period.years
                    CacheUtil.addOlderInfo(QuestionActivity.olderInfo)
                    showToast("本地保存成功")
                    eventViewModel.saveQuestionSuccess.postValue(true)
                    eventViewModel.localReport.postValue(true)
                    finish()
                    val intent = Intent(this@QuestionSupplementaryInfoActivity, ReportDetailActivity::class.java)
                    intent.putExtra(Constants.Intent_OLDER, QuestionActivity.olderInfo)
                    startActivity(intent)
                }

            }

        }
    }

    private fun getCommitData() {
        val currentDate = LocalDate.now()
        val questionnaires = mutableListOf<Questionnaire>()

        val questionnaireA = Questionnaire("认知功能评估(A)", 0, "", GroupQuestionType.COGNITION_A.value, "总得分为0-7分，为重度认知障碍；8-12分为中度认知障碍；13-15分为认知水平正常", mutableListOf(), !QuestionActivity.jumpB)

        var scoreA = 0
        //认知评估A
        if (QuestionActivity.olderInfoQuestion1.select[0].is_selected == 1) {
            scoreA++
        }
        if (QuestionActivity.olderInfoQuestion2.select[0].is_selected == 1) {
            scoreA++
        }
        if (QuestionActivity.olderInfoQuestion3.select[0].is_selected == 1) {
            scoreA++
        }
        //计算当前是哪一年的分值规则：1小问若回答正确得3分，相差1年得2分，相差2-5年得1分，其它得0分
        if (!QuestionActivity.yearIsChecked) {
            if (QuestionActivity.olderInfoQuestion4.select[0].value.toIntOrNull() != null) {
                if (QuestionActivity.olderInfoQuestion4.select[0].value.toInt() - currentDate.year == 0) {
                    scoreA += 3
                }
                if (Math.abs(QuestionActivity.olderInfoQuestion4.select[0].value.toInt() - currentDate.year) == 1) {
                    scoreA += 2
                }

                if (Math.abs(QuestionActivity.olderInfoQuestion4.select[0].value.toInt() - currentDate.year) in 2..5) {
                    scoreA += 1
                }
            }

        }


        //计算当前是哪一天的分值规则：若2小问的回答相差5天之内得2分；相差1个月以内得1分，其它为0分
        if (!QuestionActivity.monthIsChecked) {
            val dateArr = QuestionActivity.olderInfoQuestion5.select[0].value.split("-")
            if (dateArr.size == 3) {
                val year = dateArr[0].toIntOrNull()
                val month = dateArr[1].toIntOrNull()
                val day = dateArr[2].toIntOrNull()
                if (year != null && month != null && day != null) {
                    val selectedDate = LocalDate.of(year, month, day)
                    if (abs(ChronoUnit.DAYS.between(selectedDate, currentDate)) <= 5) {
                        scoreA += 2
                    } else if (abs(ChronoUnit.DAYS.between(selectedDate, currentDate)) <= 30) {
                        scoreA += 1
                    }
                }
            }
        }

        if (!QuestionActivity.weekIsChecked) {
            //计算今天星期几，若3小问回答正确得1分，答错为0分
            if (QuestionActivity.olderInfoQuestion6.select[0].value.toIntOrNull() != null) {
                if (QuestionActivity.olderInfoQuestion6.select[0].value.toInt() == currentDate.dayOfWeek.value) {
                    scoreA += 1
                }
            }
        }

        //回顾测试1回答
        if (QuestionActivity.olderInfoQuestion7.select[0].is_selected == 1) {
            scoreA += 2
        }
        if (QuestionActivity.olderInfoQuestion7.select[1].is_selected == 1) {
            scoreA += 1
        }
        if (QuestionActivity.olderInfoQuestion8.select[0].is_selected == 1) {
            scoreA += 2
        }
        if (QuestionActivity.olderInfoQuestion8.select[1].is_selected == 1) {
            scoreA += 1
        }

        if (QuestionActivity.olderInfoQuestion9.select[0].is_selected == 1) {
            scoreA += 2
        }
        if (QuestionActivity.olderInfoQuestion9.select[1].is_selected == 1) {
            scoreA += 1
        }
        questionnaireA.question.add(QuestionActivity.olderInfoQuestion1)
        questionnaireA.question.add(QuestionActivity.olderInfoQuestion2)
        questionnaireA.question.add(QuestionActivity.olderInfoQuestion3)
        questionnaireA.question.add(QuestionActivity.olderInfoQuestion4)
        questionnaireA.question.add(QuestionActivity.olderInfoQuestion5)
        questionnaireA.question.add(QuestionActivity.olderInfoQuestion6)
        questionnaireA.question.add(QuestionActivity.olderInfoQuestion7)
        questionnaireA.question.add(QuestionActivity.olderInfoQuestion8)
        questionnaireA.question.add(QuestionActivity.olderInfoQuestion9)
        if (QuestionActivity.jumpB) {//如果跳到B，标示用户没做A，
            scoreA = 0
        }
        questionnaireA.score = scoreA
        var reusltA = ""
        if (scoreA <= 7) {
            reusltA = "重度认知障碍"
        } else if (scoreA <= 12) {
            reusltA = "中度认知障碍"
        } else {
            reusltA = "认知水平正常"
        }
        questionnaireA.result = reusltA
        questionnaires.add(questionnaireA)


//            showToast("当前分数"+scoreA.toString())
        println("====A分数：${scoreA}")

        //认知B： 现在的规则就是这样的。就认知功能B部分，最终显示的相当于也就是第8题的选项结果。分数只算第6题的，但感觉第6题的分数完全没啥用，似乎都不需要算
        var scoreB = 0

        val questionnaireB = Questionnaire("认知功能评估(B)", 0, "", GroupQuestionType.COGNITION_B.value, "①认知功能正常 \n②轻度认知智障 \n③中度认知智障\n④严重认知智障", mutableListOf(), QuestionActivity.jumpB)
        questionnaireB.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[0]))
        questionnaireB.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[1]))
        questionnaireB.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[2]))
        questionnaireB.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[3]))
        questionnaireB.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[4]))
        questionnaires.add(questionnaireB)
        QuestionActivity.questions[2].options.forEach {
            if (it.isSelected) {
                scoreB++
            }
        }
        QuestionActivity.questions[4].options.forEach {
            if (it.isSelected) {
                questionnaireB.result = it.title
            }
        }
        if (!QuestionActivity.jumpB) {//如果没有跳到B，标示用户做了A，则不在做B
            scoreB = 0
        }
        questionnaireB.score = scoreB
        println("====B分数：${scoreB}  描述：${questionnaireB.result}")

        //移动能力评估
        val mobilityAssessment = Questionnaire("移动能力评估", 0, "", GroupQuestionType.LOCOMOTIVITY.value, "13-16分：移动能力良好，基本独立\n9-12分：移动能力轻度受限，可能需要少量帮助\n5-8分：移动能力中度受限，需要中等程度帮助\n0-4分：移动能力严重受限，需要大量帮助或完全依赖", mutableListOf())
        questionnaires.add(mobilityAssessment)
        var mobilityAssessmentScore = 0
        var mobilityAssessmentResult = ""
        mobilityAssessment.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[5]))
        mobilityAssessment.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[6]))
        mobilityAssessment.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[7]))
        mobilityAssessment.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[8]))
        QuestionActivity.questions[5].options.forEachIndexed { index, options ->
            if (options.isSelected) {
                mobilityAssessmentScore += index
            }
        }
        QuestionActivity.questions[6].options.forEachIndexed { index, options ->
            if (options.isSelected) {
                mobilityAssessmentScore += index
            }
        }
        QuestionActivity.questions[7].options.forEachIndexed { index, options ->
            if (options.isSelected) {
                mobilityAssessmentScore += index
            }
        }
        QuestionActivity.questions[8].options.forEachIndexed { index, options ->
            if (options.isSelected) {
                mobilityAssessmentScore += index
            }
        }

        if (mobilityAssessmentScore <= 4) {
            mobilityAssessmentResult = "移动能力严重受限，需要大量帮助或完全依赖"
        } else if (mobilityAssessmentScore <= 8) {
            mobilityAssessmentResult = "移动能力中度受限，需要中等程度帮助"
        } else if (mobilityAssessmentScore <= 12) {
            mobilityAssessmentResult = "移动能力轻度受限，可能需要少量帮助"
        } else if (mobilityAssessmentScore <= 16) {
            mobilityAssessmentResult = "移动能力良好，基本独立"
        }
        mobilityAssessment.score = mobilityAssessmentScore
        mobilityAssessment.result = mobilityAssessmentResult
        println("====移动能力：${mobilityAssessment.score}  描述：${mobilityAssessment.result}")

        //营养状况评估
        val utritionalStatus = Questionnaire("营养状况评估", 0, "", GroupQuestionType.NUTRITIONAL_STATUS.value, "0-1分：营养状况正常；\n2-3分：存在营养不良的风险；\n4分或以上：初步判断为营养不良。", mutableListOf())
        questionnaires.add(utritionalStatus)
        var utritionalStatusScore = 0
        var utritionalStatusResult = ""
        utritionalStatus.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[9]))
        utritionalStatus.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[10]))
        utritionalStatus.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[11]))
        utritionalStatus.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[12]))
        if (QuestionActivity.questions[9].options[1].isSelected) {
            utritionalStatusScore++
        } else if (QuestionActivity.questions[9].options[2].isSelected) {
            utritionalStatusScore += 2
        }
        if (QuestionActivity.questions[10].options[1].isSelected) {
            utritionalStatusScore++
        }
        if (QuestionActivity.questions[11].options[1].isSelected) {
            utritionalStatusScore++
        }
        if (QuestionActivity.questions[12].options[1].isSelected) {
            utritionalStatusScore++
        }
        if (utritionalStatusScore <= 1) {
            utritionalStatusResult = "营养状况正常"
        } else if (utritionalStatusScore <= 3) {
            utritionalStatusResult = "存在营养不良的风险"
        } else if (utritionalStatusScore > 3) {
            utritionalStatusResult = "初步判断为营养不良"
        }
        utritionalStatus.score = utritionalStatusScore
        utritionalStatus.result = utritionalStatusResult
        println("====营养状况：${utritionalStatus.score}  描述：${utritionalStatus.result}")
        //感官与沟通能力评估
        val sensoryAbility = Questionnaire("感官与沟通能力评估", 0, "", GroupQuestionType.SENSORY_ABILITY.value, "0-2分：感官与沟通能力正常\n3-5分：感官与沟通能力轻度受损\n6-8分：感官与沟通能力中度受损\n9-12分：感官与沟通能力重度受损", mutableListOf())
        questionnaires.add(sensoryAbility)
        var sensoryAbilityScore = 0
        var sensoryAbilityResult = ""
        var addLevel = false
        for (outIndex in 13 until 18) {
            sensoryAbility.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[outIndex]))
            QuestionActivity.questions[outIndex].options.forEachIndexed { index, options ->
                if (options.isSelected) {
                    sensoryAbilityScore += index
                }

                if (options.isSelected && index == QuestionActivity.questions[outIndex].options.size - 1) {
                    addLevel = true
                }
            }
        }
        //表达能力所选择的index
        var expressIndex = 0

        QuestionActivity.questions[16].options.forEachIndexed { index, options ->
            if (options.isSelected) {
                expressIndex = index
            }

        }
        //理解能力
        var understandIndex = 0
        QuestionActivity.questions[17].options.forEachIndexed { index, options ->
            if (options.isSelected) {
                understandIndex = index
            }
        }
        //如果表达能力和理解能力都大于2 ，等级+1

        if (understandIndex >= 2 && expressIndex >= 2) {
            addLevel = true
        }

        sensoryAbility.score = sensoryAbilityScore
        if (sensoryAbility.score <= 2) {
            sensoryAbilityResult = "感官与沟通能力正常"
        } else if (sensoryAbility.score <= 5) {
            sensoryAbilityResult = "感官与沟通能力轻度受损"
        } else if (sensoryAbility.score <= 8) {
            sensoryAbilityResult = "感官与沟通能力中度受损"
        } else if (sensoryAbility.score <= 12) {
            sensoryAbilityResult = "感官与沟通能力重度受损"
        }


        if (sensoryAbility.score <= 2 && addLevel) {
            sensoryAbilityScore = 4
            sensoryAbilityResult = "感官与沟通能力轻度受损"
        } else if (sensoryAbility.score <= 5 && addLevel) {
            sensoryAbilityScore = 7
            sensoryAbilityResult = "感官与沟通能力中度受损"
        } else if (sensoryAbility.score <= 8 && addLevel) {
            sensoryAbilityScore = 10
            sensoryAbilityResult = "感官与沟通能力重度受损"
        }

        sensoryAbility.score = sensoryAbilityScore
        sensoryAbility.result = sensoryAbilityResult
        println("====感官与沟通能力评估：${sensoryAbility.score}  描述：${sensoryAbility.result}")

        //抑郁症状评估
        val depressiveSymptoms = Questionnaire("抑郁症状评估", 0, "", GroupQuestionType.DEPRESSED.value, "若被评估人总分≥3分，则其可能存在抑郁倾向。\n若被评估人总分<3分，抑郁倾向较低", mutableListOf())
        questionnaires.add(depressiveSymptoms)
        var depressiveSymptomsScore = 0
        var depressiveSymptomsResult = ""
        depressiveSymptoms.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[18]))
        depressiveSymptoms.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[19]))
        QuestionActivity.questions[18].options.forEachIndexed { index, options ->
            if (options.isSelected) {
                depressiveSymptomsScore += index
            }
        }
        QuestionActivity.questions[19].options.forEachIndexed { index, options ->
            if (options.isSelected) {
                depressiveSymptomsScore += index
            }
        }
        if (depressiveSymptomsScore >= 3) {
            depressiveSymptomsResult = "可能存在抑郁倾向"
        } else if (depressiveSymptomsScore < 3) {
            depressiveSymptomsResult = "抑郁倾向较低"
        }
        depressiveSymptoms.score = depressiveSymptomsScore
        depressiveSymptoms.result = depressiveSymptomsResult
        println("====抑郁症状评估：${depressiveSymptoms.score}  描述：${depressiveSymptoms.result}")

        //大小便控制能力评估
        val toiletControl = Questionnaire("大小便控制能力评估", 0, "", GroupQuestionType.DEFECATION.value, "\n0分：完全正常\n1-3分：轻中度障碍\n4-6分：重度障碍\n7-8分：极重度障碍", mutableListOf())
        questionnaires.add(toiletControl)
        var toiletControlScore = 0
        var toiletControlResult = ""
        toiletControl.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[20]))
        toiletControl.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[21]))
        QuestionActivity.questions[20].options.forEachIndexed { index, options ->
            if (options.isSelected) {
                toiletControlScore += index
            }
        }
        QuestionActivity.questions[21].options.forEachIndexed { index, options ->
            if (options.isSelected) {
                toiletControlScore += index
            }
        }


        if (toiletControlScore == 0) {
            toiletControlResult = "完全正常"
        } else if (toiletControlScore <= 3) {
            toiletControlResult = "轻中度障碍"
        } else if (toiletControlScore <= 6) {
            toiletControlResult = "重度障碍"
        } else if (toiletControlScore <= 8) {
            toiletControlResult = "极重度障碍"
        }
        toiletControl.score = toiletControlScore
        toiletControl.result = toiletControlResult
        println("====大小便控制能力评估：${toiletControl.score}  描述：${toiletControl.result}")

        //基本日常生活活动能力相关问题
        val basicDailyLife = Questionnaire("基本日常生活活动能力相关问题", 0, "", GroupQuestionType.DAILY_LIFE_A.value, "0-20分：完全依赖\n21-60分：严重依赖\n61-90分：中度依赖\n91-99分：轻度依赖\n100分：独立", mutableListOf())
        questionnaires.add(basicDailyLife)
        var basicDailyLifeScore = 0
        var basicDailyLifeResult = ""

        for (index in 22 until 29) {
            QuestionActivity.questions[index].options.forEachIndexed { index, options ->
                if (options.isSelected) {
                    basicDailyLifeScore += index * 5
                }

            }
            basicDailyLife.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[index]))
        }
        //由于之前的积分不可能到达100分，所以增加以下逻辑
        QuestionActivity.questions[20].options.forEachIndexed { index, options ->
            if (index == 0 && options.isSelected) {
                basicDailyLifeScore += 10
            } else if (index == 1 && options.isSelected) {
                basicDailyLifeScore += 5
            }
        }
        QuestionActivity.questions[21].options.forEachIndexed { index, options ->
            if (index == 0 && options.isSelected) {
                basicDailyLifeScore += 10
            } else if (index == 1 && options.isSelected) {
                basicDailyLifeScore += 5
            }
        }
        var absoluteDependence = false
        var help = false//需要大量帮助
        var lessHelp = false//需要少量帮助
        QuestionActivity.questions[5].options.forEachIndexed { index, options ->
            if (index == 0 && options.isSelected) {
                absoluteDependence = true
            } else if (index == 1 && options.isSelected) {
                help = true
            } else if (index == 2 && options.isSelected) {
                lessHelp = true
            }
        }
        QuestionActivity.questions[6].options.forEachIndexed { index, options ->
            if (index == 0 && options.isSelected) {
                absoluteDependence = true
            } else if (index == 1 && options.isSelected) {
                help = true
            } else if (index == 2 && options.isSelected) {
                lessHelp = true
            }
        }
        QuestionActivity.questions[7].options.forEachIndexed { index, options ->
            if (index == 0 && options.isSelected) {
                absoluteDependence = true
            } else if (index == 1 && options.isSelected) {
                help = true
            } else if (index == 2 && options.isSelected) {
                lessHelp = true
            }
        }
        QuestionActivity.questions[8].options.forEachIndexed { index, options ->
            if (index == 0 && options.isSelected) {
                absoluteDependence = true
            } else if (index == 1 && options.isSelected) {
                help = true
            } else if (index == 2 && options.isSelected) {
                lessHelp = true
            }
        }

        //如果完全依赖，不加分
        if (absoluteDependence) {

        } else if (help) {
            basicDailyLifeScore += 5
        } else if (lessHelp) {
            basicDailyLifeScore += 10
        } else {
            basicDailyLifeScore += 15
        }
        if (basicDailyLifeScore <= 20) {
            basicDailyLifeResult = "完全依赖"
        } else if (basicDailyLifeScore <= 60) {
            basicDailyLifeResult = "严重依赖"
        } else if (basicDailyLifeScore <= 90) {
            basicDailyLifeResult = "中度依赖"
        } else if (basicDailyLifeScore <= 99) {
            basicDailyLifeResult = "轻度依赖"
        } else if (basicDailyLifeScore == 100) {
            basicDailyLifeResult = "独立"
        }

        basicDailyLife.score = basicDailyLifeScore
        basicDailyLife.result = basicDailyLifeResult
        println("====基本日常生活活动能力相关问题：${basicDailyLife.score}  描述：${basicDailyLife.result}")

        //工具性日常生活活动能力
        val toolsDailyLife = Questionnaire("工具性日常生活活动能力", 0, "", GroupQuestionType.DAILY_LIFE_B.value, "0-2分：严重依赖\n3-5分：中度依赖\n6-8分：轻度依赖或独立", mutableListOf())
        questionnaires.add(toolsDailyLife)
        var toolsDailyLifeScore = 0
        var toolsDailyLifeResult = ""

        for (index in 29 until 37) {
            toolsDailyLife.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[index]))
        }
        if (!QuestionActivity.questions[29].options[3].isSelected) {
            toolsDailyLifeScore++
        }
        if (QuestionActivity.questions[30].options[0].isSelected) {
            toolsDailyLifeScore++
        }
        if (QuestionActivity.questions[31].options[0].isSelected) {
            toolsDailyLifeScore++
        }

        if (!QuestionActivity.questions[32].options[4].isSelected) {
            toolsDailyLifeScore++
        }

        if (!QuestionActivity.questions[33].options[2].isSelected) {
            toolsDailyLifeScore++
        }
        if (QuestionActivity.questions[34].options[0].isSelected) {
            toolsDailyLifeScore++
        }

        if (QuestionActivity.questions[35].options[0].isSelected) {
            toolsDailyLifeScore++
        }
        if (!QuestionActivity.questions[36].options[2].isSelected) {
            toolsDailyLifeScore++
        }
        if (toolsDailyLifeScore <= 2) {
            toolsDailyLifeResult = "严重依赖"
        } else if (toolsDailyLifeScore <= 5) {
            toolsDailyLifeResult = "中度依赖"
        } else {
            toolsDailyLifeResult = "轻度依赖或者独立"
        }
        toolsDailyLife.score = toolsDailyLifeScore
        toolsDailyLife.result = toolsDailyLifeResult
        println("====工具性日常生活活动能力：${toolsDailyLife.score}  描述：${toolsDailyLife.result}")
        var selectedNotUse = false
        for (index in 29 until 37) {
            if (QuestionActivity.questions[index].options[QuestionActivity.questions[index].options.size-1].isSelected) {
                selectedNotUse = true
            }
        }
        //如果选项里面有不适用整个模块不显示
        if (selectedNotUse) {
            toolsDailyLife.is_show=false
        }
        //跌倒相关问题
        val fallingTo = Questionnaire("跌倒相关问题", 0, "", GroupQuestionType.TAKE_CARE_OF.value, "", mutableListOf(), false)
        questionnaires.add(fallingTo)

        for (index in 37 until 40) {
            fallingTo.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[index]))
        }


        //压疮相关问题
        val PressureUlcer = Questionnaire("压疮相关问题", 0, "", GroupQuestionType.TAKE_CARE_OF.value, "", mutableListOf(), false)
        questionnaires.add(PressureUlcer)
        for (index in 40 until 45) {
            PressureUlcer.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[index]))
        }

        //疼痛相关问题
        val pain = Questionnaire("疼痛相关问题", 0, "", GroupQuestionType.TAKE_CARE_OF.value, "", mutableListOf(), false)
        questionnaires.add(pain)
        for (index in 45 until 50) {
            pain.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[index]))
        }


        //创口护理相关问题
        val woundCare = Questionnaire("创口护理相关问题", 0, "", GroupQuestionType.TAKE_CARE_OF.value, "", mutableListOf(), false)
        questionnaires.add(woundCare)
        for (index in 50 until 56) {
            woundCare.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[index]))
        }


        //其他护理相关问题
        val otherWoundCare = Questionnaire("其他护理相关问题", 0, "", GroupQuestionType.TAKE_CARE_OF.value, "", mutableListOf(), false)
        questionnaires.add(otherWoundCare)
        for (index in 56 until 59) {
            otherWoundCare.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[index]))
        }

        //照顾服务使用情况
        val careServices = Questionnaire("照顾服务使用情况", 0, "", GroupQuestionType.CARE_SERVICES.value, "", mutableListOf(), false)
        questionnaires.add(careServices)
        for (index in 59 until 62) {
            careServices.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[index]))
        }


        //家庭照护情况
        val homeCareServices = Questionnaire("家庭照护情况", 0, "", GroupQuestionType.CARE_SERVICES.value, "", mutableListOf(), false)
        questionnaires.add(homeCareServices)
        for (index in 62 until 67) {
            homeCareServices.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[index]))
        }

        //正式照护服务使用情况
        val formalCareServices = Questionnaire("正式照护服务使用情况", 0, "", GroupQuestionType.CARE_SERVICES.value, "", mutableListOf(), false)
        questionnaires.add(formalCareServices)
        for (index in 67 until 74) {
            formalCareServices.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[index]))
        }


        //医疗服务利用情况
        val medicalService = Questionnaire("医疗服务利用情况", 0, "", GroupQuestionType.MEDICAL_SERVICE.value, "", mutableListOf(), false)
        questionnaires.add(medicalService)
        for (index in 74 until 87) {
            medicalService.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[index]))
        }
        QuestionActivity.olderInfo.questionnaire = questionnaires

        //作答情况统计
        val statistics = Questionnaire("作答情况统计", 0, "", GroupQuestionType.STATISTICS.value, "", mutableListOf(), false)
        questionnaires.add(statistics)
        for (index in 87 until 89) {
            statistics.question.add(questions2OlderInfoQuestion(QuestionActivity.questions[index]))
        }
        QuestionActivity.olderInfo.questionnaire = questionnaires
    }

    fun questions2OlderInfoQuestion(question: Questions): OlderInfoQuestion {
        val olderInfo = OlderInfoQuestion(question.questionTitle, mutableListOf())
        question.options.forEach {
            olderInfo.select.add(Select(it.title, if (it.isSelected) 1 else 0, it.value))
        }
        return olderInfo
    }

    fun showDateDialog() {
        val currentDate = LocalDate.now()
        val picker = DatePicker(this)
        picker.setBackgroundResource(R.drawable.bg_white_top_round_8)
        picker.setTitle("评估日期")
        val wheelLayout = picker.wheelLayout
        wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
        wheelLayout.setDateLabel("", "", "")
        wheelLayout.setDateFormatter(UnitDateFormatter())
        wheelLayout.setRange(DateEntity.target(1928, 1, 1), DateEntity.target(currentDate.year, currentDate.monthValue, currentDate.dayOfMonth), DateEntity.today())
        wheelLayout.setCurtainEnabled(false)
        wheelLayout.setIndicatorEnabled(false)
        picker.wheelLayout.setResetWhenLinkage(false)
        picker.setOnDatePickedListener(this)
        picker.show()
    }

    override fun onDatePicked(year: Int, month: Int, day: Int) {
        mViewModel.date.set("${year}-${String.format("%02d", month)}-${String.format("%02d", day)}")
    }
}